/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Controlador;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Entidades.EntUsuario;
import Negocio.UsuarioN;
import Persistencia.Daos;
import Utilidades.Conexion;
import java.sql.Connection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.Cookie;

/**
 *
 * @author santiago
 */
@WebServlet(name = "SvlAutenticacion", urlPatterns = {"/SvlAutenticacion"})
public class SvlAutenticacion extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String usuario = request.getParameter("usuario");
        String clave = request.getParameter("clave");
        UsuarioN n = new UsuarioN();
        EntUsuario u = new EntUsuario();
        try {
            u = n.ValidarIngreso(clave, usuario);
            if (u != null) {
                if ((usuario.equals(u.getNumeroDocumento())) && (clave.equals(u.getClave()))) {
                    Cookie userCookie = new Cookie("usuario", u.getNumeroDocumento());
                    Cookie perfilCookie = new Cookie("perfil", u.getTipo());
                    Cookie nickCookie=new Cookie("nick",u.getNick());
                    //setting cookie to expiry in 30 mins
                    userCookie.setMaxAge(30 * 60);
                    perfilCookie.setMaxAge(30 * 60);
                    response.addCookie(userCookie);
                    response.addCookie(perfilCookie);
                    response.addCookie(nickCookie);
                    response.sendRedirect("index.jsp");
                    System.out.println("entro");
                }
                if (u.getNumeroDocumento().equals("No existe")) {
                    request.setAttribute("mensajeError", "Usuario y/o contraseña incorrectos");
                    request.getRequestDispatcher("login.jsp").forward(request, response);
                }

            }
        } catch (Exception ex) {
            Logger.getLogger(EntUsuario.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("mensajeError", " Usuario y/o contraseña incorrectos");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
        try {

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
        Daos usuarioDAO = new Daos();
        Conexion con = new Conexion();
        Connection c = con.getCon();
        String user = request.getParameter("usuario");
        String pass = request.getParameter("clave");
        EntUsuario usuario;
        try {
            usuario = usuarioDAO.ValidarUsuario(c, user, pass);
            if (user.equals(usuario.getNumeroDocumento()) && pass.equals(usuario.getClave())) {
                Cookie loginCookie = new Cookie("usuario", usuario.getNumeroDocumento());
                Cookie perfilCookie = new Cookie("perfil", usuario.getTipo());
                Cookie nickCookie = new Cookie("nick", usuario.getNick());
                //setting cookie to expiry in 30 mins
                loginCookie.setMaxAge(30 * 60);
                nickCookie.setMaxAge(30 * 60);
                perfilCookie.setMaxAge(30 * 60);
                response.addCookie(loginCookie);
                response.addCookie(nickCookie);
                response.addCookie(perfilCookie);
                response.sendRedirect("index.jsp");
                System.out.println("entro");
                //request.getRequestDispatcher("Inicio.jsp").forward(request, response);
            } else {

                System.out.println("No entro");
                request.setAttribute("mensajeError", "Usuario y/o contraseña incorrectos");
                request.getRequestDispatcher("login.jsp").forward(request, response);

            }
        } catch (Exception ex) {
            Logger.getLogger(EntUsuario.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("mensajeError", " Usuario y/o contraseña incorrectos");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
